<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :left-show="false">
        <template #after>
          <el-button
            type="danger"
            size="small"
            @click="$router.push('/employees/import')"
          >导入</el-button>
          <el-button
            type="warning"
            size="small"
            @click="exportExcel"
          >导出</el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            :disabled="isDisabled(point.userAdd)"
            @click="dialogVisible = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <!-- 表格 -->
      <!-- 放置表格和分页 -->
      <el-card style="margin: 10px 0">
        <el-table border :data="employeesData">
          <el-table-column
            label="序号"
            align="center"
            sortable
            type="index"
            width="80"
          />
          <el-table-column
            align="center"
            label="姓名"
            sortable
            prop="username"
          />
          <el-table-column
            align="center"
            label="头像"
            sortable
          >
            <template slot-scope="{row}">
              <img :src="row.staffPhoto" class="staffPhoto" @click="showCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="工号"
            sortable
            prop="workNumber"
          />
          <el-table-column
            align="center"
            label="聘用形式"
            sortable
            prop="formOfEmployment"
            :formatter="formatterType"
          />
          <el-table-column
            align="center"
            label="部门"
            sortable
            prop="departmentName"
          />
          <el-table-column align="center" label="入职时间" sortable>
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatTime }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="账户状态"
            sortable
            prop="enableState"
          />
          <el-table-column
            align="center"
            label="操作"
            sortable
            fixed="right"
            width="280"
          >
            <template slot-scope="{row}">
              <el-button type="text" size="small" :disabled="isDisabled(point.userUpdate)" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small" :disabled="isDisabled(point.userZz)">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="isDisabled(point.userDel)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :total="total"
            :current-page="query.page"
            :page-size="query.size"
            layout="prev, pager, next"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
    </div>

    <!-- 新增员工弹层 -->
    <add-dialog :visible.sync="dialogVisible" @add-success="loadEmployees" />

    <!-- 员工头像二维码弹层 -->
    <el-dialog
      title="二维码"
      :visible.sync="qrCodeDialogVisible"
      width="30%"
    >
      <el-row type="flex" justify="center">
        <canvas ref="code" />
      </el-row>
    </el-dialog>

    <!-- 修改员工角色弹层 -->
    <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import QRCode from 'qrcode'
import { getEmployeesList } from '@/api/employees'
import employees from '@/api/constant/employees'
import AddDialog from './components/AddDialog.vue'
import { formatTime } from '@/filter'
import AssignRole from './components/AssignRole.vue'

import mixinsPoint from '@/mixins/point'
const { hireType } = employees
const userRelations = {
  姓名: 'username',
  手机号: 'mobile',
  入职日期: 'timeOfEntry',
  聘用形式: 'formOfEmployment',
  转正日期: 'correctionTime',
  工号: 'workNumber',
  部门: 'departmentName'
}
export default {
  name: 'Employees',
  components: { AddDialog, AssignRole },

  mixins: [mixinsPoint],
  data() {
    return {
      employeesData: [],

      query: {
        page: 1,
        size: 5
      },
      total: 0,
      dialogVisible: false,
      qrCodeDialogVisible: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.loadEmployees()
  },

  methods: {
    async loadEmployees() {
      const res = await getEmployeesList(this.query)
      this.total = res.total
      this.employeesData = res.rows
    },
    currentChange(val) {
      this.query.page = val
      this.loadEmployees()
    },
    formatterType(row, column, cellValue, index) {
      const findItem = hireType.find((item) => item.id === cellValue)
      return findItem ? findItem.value : '未知'
    },
    async exportExcel() {
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      const multiHeader = [['姓名', '个人信息', '', '', '', '', '部门']]
      const tableHeader = Object.keys(userRelations)// ['手机号','姓名'...]
      const { rows } = await getEmployeesList({ page: 1, size: this.total })// [{},{}...]
      const data = rows.map((item) => tableHeader.map((key) => {
        if (key === '入职日期' || key === '转正日期') {
          return formatTime(item[userRelations[key]])
        } else if (key === '聘用形式') {
          const i = hireType.find(item1 => item1.id === item[userRelations[key]])
          return i ? i.value : '未知'
        } else {
          return item[userRelations[key]]
        }
      })) // item:{mobile,username...} key:'姓名'
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: tableHeader, // 表头 必填
          merges: merges,
          multiHeader,
          data: data, // 具体数据 必填
          filename: '员工列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    showCode(imgUrl) {
      if (!imgUrl) return this.$message.error('图片不存在')
      this.qrCodeDialogVisible = true
      this.$nextTick(_ => {
        QRCode.toCanvas(this.$refs.code, imgUrl)
      })
    },
    editRole(id) {
      this.showRoleDialog = true
      this.userId = id
    }
  }
}
</script>

<style scoped lang="scss">
.staffPhoto{
  width: 80px;
  height: 80px;
  border-radius: 50%;
}
</style>
